﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using HNQXYJ.BLL;
using HNQXYJ.DAL.DSSysConfigTableAdapters;


namespace HNQXYJ.DAL
{
    /// <summary>
    /// 用来负责监听下位机socket类
    /// </summary>
    public static class SOCK
    {
        static Thread threadWatch = null;
        static Socket socketWatch = null;
        static bool Flage = false;
       
       
        /// <summary>
        /// 开始监听客户端的消息
        /// </summary>
        public static void BtnBeginListen()
        {

            string ipAddress = SqlHelper.IP; //"192.168.1.131";//获取ip地址 （可以动态修改）
            int port = SqlHelper.Port ;  //8888;//服务器端的端口号，（可以动态修该）
            //创建服务器端负责监听的套接字。参数（使用ip4寻址协议，使用流式连接方式，使用tcp传输协议）
            socketWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            //将字符串转换为ip地址
            IPAddress address = IPAddress.Parse(ipAddress);
            //创建包含ip和port的网络节点对象
            IPEndPoint endPoint = new IPEndPoint(address, port);
            //将负责监听的套接字绑定到唯一的ip和端口上
            socketWatch.Bind(endPoint);
            //设置监听队列的长度
            socketWatch.Listen(10);
            //创建负责监听的线程，并传入监听方法
            threadWatch = new Thread(WatchConnecting);
            //设置线程为后台线程
            threadWatch.IsBackground = true;
            //开启线程
            threadWatch.Start();
            Flage = true;
        }


        static Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
        static Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
        /// <summary>
        /// 监听客户端请求的方法
        /// </summary>
        static void WatchConnecting()
        {
            //持续不断的监听客户端的连接请求
            while (true)
            {
                try
                {
                    //开始监听客户端连接请求，Accept方法会阻断当前线程。
                    //一旦监听到客户端请求，就返回一个和
                    Socket soKConnection = socketWatch.Accept();
                    Thread thr = new Thread(RecMsg);
                    thr.IsBackground = true;
                    thr.Start(soKConnection);
                }
                catch (Exception ex)
                {
 
                }
 
            }
           
        }

        public static string strMsgRec = "";

        /// <summary>
        /// 服务器端负责监听客户端发送来的数据的方法
        /// </summary>
        /// <param name="socketClientPara"></param>
        static void RecMsg(object socketClientPara)
        {
            Socket socketClient = socketClientPara as Socket;
            EndPoint remoteEndPoint = socketClient.RemoteEndPoint;
            string phoneKey = "";
            while (true)
            {
                byte[] arrMsgRec = new byte[1024 * 1024];
                socketClient.ReceiveTimeout = 420000;//心跳间隔设置为7分钟
                int length = -1;
                try
                {
                    //接收到的数据的实际长度
                    length = socketClient.ReceiveFrom(arrMsgRec, ref remoteEndPoint);
                    //将接受到的数据转化为字符串的形式
                    strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, length);
                    char strheader = strMsgRec[0];
                    phoneKey = strMsgRec.Substring(2, 11);

                    //处理客户端心跳包 能得到R说明终端是在线的 更新一下终端的在线状态
                    if (strheader == 'R')
                    {
                        if (!dict.ContainsKey(phoneKey))
                        {
                            //套接字字典中如果没有该套接字（第一次连接或者是断开后重新连接） 就添加进去
                            dict.Add(phoneKey, socketClient);
                        }
                        else
                        {
                            dict[phoneKey] = socketClient;
                        }
                        UpdateTerminalStatus(phoneKey, "在线");
                    }

                    if (strheader == 'D')
                    {
                        // 发送信息成功后的返回数据

                    }
                    if (strheader == 'P')
                    {
                        //断电处理 
                    }


                }
                catch (SocketException ex)
                {
                    //异常情况作离线处理 收不到心跳包说明终端下线，更新数据库中的终端状态（下线）
                    UpdateTerminalStatus(phoneKey, "离线");
                    
                }
                catch (Exception ex)
                {
                    UpdateTerminalStatus(phoneKey, "离线");

                }
            }
 
        }

        /// <summary>
        /// 开启监听
        /// </summary>
        public static void StartListen()
        {
            if (Flage)
            {
                return;//监听如果已经开启就直接返回


            }
            else
            {
                BtnBeginListen();//开启监听

            }
        }

        //终止监听
        public static void btnEndListen()
        {
            //socketWatch.Shutdown(SocketShutdown.Both);
            Flage = false;
            socketWatch.Close();
            threadWatch.Abort();

        }

        //更新终端表状态
        public static void UpdateTerminalStatus(string phone,string status)
        {
            int res = TerminalBLL.UpdateTerminalStatusByPhone(phone, status);
        }


        /// <summary>
        /// 向终端发送数据
        /// </summary>
        /// <param name="list">终端列表</param>
        /// <param name="msg">发送的信息</param>
        /// <param name="sendTimes">发送次数</param>
        public static void SendMessage(List<string> list, string msg, string sendTimes)
        {
            string header = "D 12345678";
            string strMsg = header + sendTimes + msg;
            byte[] arrMsg = System.Text.Encoding.GetEncoding("gb2312").GetBytes(strMsg);
            for (int i = 0; i < list.Count; i++)
            {
                if (dict.ContainsKey(list[i]))
                {
                    dict[list[i]].Send(arrMsg);
                    //InsertHistoryInfo(list[i], sendTimes + msg, "成功");

                }
                else
                {
                   // InsertHistoryInfo(list[i], sendTimes + msg, "失败");

                }
            }
 
        }

    }
}